// let config = JSON.stringify(wx.getExtConfigSync()) !== '{}' ? wx.getExtConfigSync() : require('config.js');
let { config } = require('common/utils/ws/ws-config.js');
let util = require('common/utils/util.js');
let WxNotificationCenter = require('common/utils/WxNotificationCenter/WxNotificationCenter.js');
const { doLogin } = require('/common/utils/ws/wsxcx-opendata-sdk');

// 登录初始化  app.onLanuch或者onShow(?)的生命周期逻辑走此处的promise
// 其他页面初始化时都不需要 login，因为APP此处已经登录过了，需要的做的应该是getOpenID，除非是获取手机号的页面需要doLogin
// 其次，页面业务逻辑还是走util.request，如果41009则自动login的逻辑不变。
wx.loginPromise = doLogin();

// 系统信息
wx.systemInfo = wx.getSystemInfoSync();

// TODO, getTabbarColor aliasShow等接口重复请求。


let appConfig = {
  INJECT_BLOBAL_EVENT: 'INJECT_BLOBAL_EVENT',
  injectGlobal: function ({ global, module }) {
    extendAppConfig(global, this);
    module && this.onLaunch({ modules: module });
  },
  onLaunch: function (ops) {
    this.modules = ops.modules || config.module;
    if (this.modules === 'ws_guangdianyun') {
      require('./common/runtime.js');
      require('./common/vendor.js');
      require('./common/main.js');
    }
    ops.modules && (this.siteInfo.module = ops.modules);
    let scene = ops.scene || 0;
    let that = this;
    // ops.scene 1011 - 1013, 1047 - 1049
    let isFromQRCode = [1011, 1012, 1013, 1047, 1048, 1049].indexOf(scene) > -1;
    let parsedOptions = util.parseOptions(ops.query || {});
    this.isFromQRCode = isFromQRCode;
    this.parsedOptions = parsedOptions;
    WxNotificationCenter.addOnceNotification('previewMiniApp', function() {
      parsedOptions.aid && parsedOptions.i && parsedOptions.t && util.request({
        url: 'auth/session/copyright',
        data: {
          uniacid: parsedOptions.i,
        },
        success: function(res) {
          let { token } = res.data.data;
          that.siteInfo.acid = parsedOptions.aid;
          that.siteInfo.uniacid = parsedOptions.i;
          that.siteInfo.multiid = parsedOptions.t;
          that.siteInfo.token = token;
          token && wx.reLaunch({
            url: '/' + getCurrentPages().pop().route,
          });
        },
      });
      wx.hideLoading();
    }, that);

    if (config.appJson && config.appJson.length > 1) {
      WxNotificationCenter.addOnceNotification(that.INJECT_BLOBAL_EVENT, that.injectGlobal, that);
    }

    // 监听openid，用于分享绑定上下级 add by liuhongyang at 2018/11/07
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid') || (wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').openid);
    if (!openid) {
      WxNotificationCenter.addOnceNotification('hasLogined', function(openID) {
        that.bindFrom(openID, ops);
      }, that);
    } else {
      this.bindFrom(openid, ops);
    }

    // 通过接口动态获取模块主题色
    this.setThemeDynamic && typeof this.setThemeDynamic === 'function' && this.setThemeDynamic(this);
    // 通过接口动取页面通用配置，如导航栏title、分享title。
    this.getPageCommonConfig(7200);

    // 从APP过来，场景值分别对应为：1036/1069/1089/1090
    if ([1036, 1069, 1089, 1090].indexOf(scene) > -1) {
      wx.setStorageSync('isFromApp', true);
      // return false; // TODO, check whether return false is necessary.
    }

    if (!ops.modules && this.modules !== 'ws_examination') {
      this.countEnterTimes();
    }

    // 企业微信。
    if (wx.systemInfo.environment === 'wxwork') {
      wx.setStorageSync('isWXWork', true); // 还保留
      this.isWXWork = true;
    }
  },

  bindFrom(openID, ops) {
    let that = this;
    if (!ops.query) return;
    let opsData = that.util.parseOptions(ops.query);
    let { openid, share_scene } = opsData;
    if (Number(share_scene) === 4) {
      setTimeout(function() {
        that.util.request({
          url: 'card/api/bind_from',
          data: {
            openid: openID,
            from_openid: openid,
            share_scene: share_scene,
          },
          success: function success() {
            console.log('绑定上下级成功！');
          },
        });
      }, 500);
    }
  },

  // 异常页面兼容[打开的小程序页面不存在，则跳转到小程序首页]
  onPageNotFound(res) {
    let page = config.appJson[0].homePage;
    util.navigateTo(page, {}, false);
  },

  onShow: function (ops) {
    // let that = this;
    if (this.isFromQRCode && !this.isShowedPreviewConfirm && this.parsedOptions.aid && this.parsedOptions.i && this.parsedOptions.t) {
      this.isShowedPreviewConfirm = true;
      wx.showLoading({
        title: '加载中',
      });
          WxNotificationCenter.postNotificationName('previewMiniApp', {});
        }
    // this.isFromQRCode && !this.isShowedPreviewConfirm && this.parsedOptions.aid && this.parsedOptions.i && this.parsedOptions.t && wx.showModal({
    //   title: '预览小程序',
    //   content: '点击确定进入小程序预览，预览以界面展示为主，部分功能可能无法正常使用。',
    //   showCancel: true,
    //   success: res => {
    //     if (res.confirm) {
    //       that.isShowedPreviewConfirm = true;
    //       WxNotificationCenter.postNotificationName('previewMiniApp', {});
    //     }
    //   },
    // });

    try {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function(res) { console.log(res) });
      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，重启应用？',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              updateManager.applyUpdate();
            }
          },
        });
      });
    } catch (error) {
      // TODO 说明基础库版本号低于1.9.90，需提示
      console.log(error);
    }

    // 客户端基础库版本兼容提示
    try {
      const sys = wx.systemInfo;
      const compareResult = this.compareVersion(sys.SDKVersion, '1.9.8');
      if (Number(compareResult !== 1)) {
        wx.showModal({
          title: '注意！',
          content: '微信版本过低，将无法顺利使用本小程序，请下载最新版微信。手机型号：' + sys.model + ' 微信版本号：' + sys.version + '基础库版本：' + sys.SDKVersion,
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#3CC51F',
        });
      }
    } catch (error) {
      console.log(error);
    }
    // TODO, 记录时间戳
    this.v8_last_app_show_time = Date.now();
    // options.modules !== 'ws_micro_shop' && util.switchDebug();
  },

  onHide: function () {
    // 记录时间戳 并计算累加
    this.v8_last_app_hide_time = Date.now();
  },

  onError: function(msg) {
    console.error(msg);
  },

  fakeOnLaunch: function (ops) {
    // TODO，拼接模块使用 模拟app onlaunch的行为
  },

  themeData: config.theme_data || {},

  // 小程序基础版本库的大小比较
  compareVersion: function (p1, p2) {
    let v1 = p1.split('.');
    let v2 = p2.split('.');
    let len = Math.max(v1.length, v2.length);
    while (v1.length < len) {
      v1.push('0');
    }
    while (v2.length < len) {
      v2.push('0');
    }
    for (let i = 0; i < len; i++) {
      let num1 = parseInt(v1[i], 10);
      let num2 = parseInt(v2[i], 10);
      if (num1 > num2) {
        return 1;
      } else if (num1 < num2) {
        return -1;
      }
    }
    return 0;
  },

  siteInfo: config, // TODO, 后台可以动态改变内容的地方，引用此值会不支持授权接入的小程序
  modules: '',
  util: util,
  // api: require('common/utils/api.js'),
  // 新版商城
  webRoot: null,

  // 小程序导航顶部的值，
  tabbarindex: 0,
  utils: require('common/utils/utilkeshihua'),
  access_token: function (_this) {
    let key = function (_this) {
      // 单商户商城
      if (!wx.getStorageSync('access_token')) {
        wx.hideLoading();
        return _this.setData({ getUserInfo: true });
      } else {
        wx.checkSession({
          success: function () {
            return false;
          },
          fail: function (res) {
            wx.hideLoading();
            return _this.setData({ getUserInfo: true });
          },
        });
      }

    };
    return key(_this);
  },
  globalData: {
    isCos: false,
    isChecked: false,
  },
  tabInfo: config.appJson || '',
  // 用户打开小程序次数统计
  countEnterTimes() {
    let { module: moduleName } = config;
    let that = this;
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
    if (!openid) {
      let userInfo = wx.getStorageSync('userInfo');
      openid = userInfo && userInfo.openid;
      if (openid) {
        that.sendRequset(openid);
      } else {
        if (moduleName === 'ws_micro_shop') {
          // this.ws_micro_shoplogin().then(res => {
          //   openid = wx.getStorageSync('OPENID');
          //   console.log('openid from micro shop storage after login:', openid);
          //   util.request({
          //     url: 'card/api/sum_visit',
          //     data: { openid },
          //   });
          // });
        } else {
          // WxNotificationCenter.postNotificationName('doLogin', 'Start login');
          wx.loginPromise.then(res => {
            // openid = res.openid || res.data.data.openid;
            WxNotificationCenter.postNotificationName('hasLogined', res.openID);
            that.sendRequset(openid);
          });
        }
      }
    } else {
      that.sendRequset(openid);
    }
  },
  sendRequset(openid) {
    let sessionid = wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').sessionid || '';
    let { siteroot, uniacid, multiid, version, module }  = config;
    wx.request({
      url: siteroot + '?i=' + uniacid + '&t=' + multiid + '&v=' + version + '&from=wxapp&m=' + module + '&c=card&a=api&do=sum_visit&state=v8uuid-' + sessionid,
      data: { openid },
      success: function() {
        // console.log('');
      },
      fail: function(e) {
        console.log(JSON.stringify(e));
      },
      complete: function() {
        // console.log('');
      },
    });
  },

  // 获取页面通用配置
  // cacheTime 单位s
  getPageCommonConfig: function(cacheTime) {
    let pageCommonConfigStorage = wx.getStorageSync('pageCommonConfig');
    let timeStamp = pageCommonConfigStorage && pageCommonConfigStorage.timeStamp;
    let nowTime = Date.now();
    let needRequest = !timeStamp || (nowTime - Number(timeStamp)) / 1000 >= Number(cacheTime);
    needRequest && this.requestPageConfig().then((res) => {
      let { appJson } = config;
      let pageCommonConfig = {};
      pageCommonConfig.timeStamp = Date.now();
      appJson.forEach((item) => {
        let filtedData = res.filter((value) => {
          return value.module === item.module;
        });
        pageCommonConfig[item.module + '_pageCommonConfig'] = filtedData;
      });
      WxNotificationCenter.postNotificationName('getPageCommonConfig', pageCommonConfig);
      wx.setStorageSync('pageCommonConfig', pageCommonConfig);
    });
  },

  requestPageConfig: function () {
    let sessionid = wx.getStorageSync('userInfo').sessionid || '';
    let { siteroot, uniacid, multiid, version, module } = config;

    return new Promise((resolve) => {
      wx.loginPromise.then((res) => {
        wx.request({
          url: `${siteroot}?i=${uniacid}&t=${multiid}&v=${version}&from=wxapp&m=${module}&c=wxapp&a=home&do=wxapp_path&state=v8uuid-${sessionid}`,
          data: { openid: res.openID },
          success: function (res) {
            if (Number(res.data.errno) === 0 && res.data.data && res.data.data instanceof Array && res.data.data.length > 0) {
              resolve(res.data.data);
            }
          },
        });
      });
    });
  },
};

function extendAppConfig(global, appConfig) {
  for (let prop in global) {
    if (global.hasOwnProperty(prop) && prop !== 'onLaunch' && prop !== 'onShow' && prop !== 'onHide' && prop !== 'onError' && prop !== 'onPageNotFound') {
      appConfig[prop] = global[prop];
    }
  }
  const { onLaunch, onShow, onHide, onError, onPageNotFound } = global;
  extendFunction(onLaunch, appConfig);
  extendFunction(onShow, appConfig);
  extendFunction(onHide, appConfig);
  extendFunction(onError, appConfig);
  extendFunction(onPageNotFound, appConfig);
}

function extendFunction(func, config) {
  if (!func || typeof func !== 'function') {
    return;
  }
  const funcName = func.name;
  const origin = config[funcName];
  config[funcName] = function (options) {
    if (origin) {
      origin.call(this, options);
    }
    func.call(this, options);
  };
}

// 页面级的分享行为处理、navigationBarTitle设置。
const originalPage = Page;
Page = function(_config) {
  const app = getApp();
  const { onShareAppMessage, onLoad, onShow, onHide, onUnload } = _config;

  // 分享行为处理
  if (typeof onShareAppMessage === 'function') {
    _config.onShareAppMessage = function(options) {
      const returnValue = onShareAppMessage.call(this, options) || {};

      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const url = currentPage.route;
      const urlOptions = currentPage.options;
      let currentPath = `/${url}?`;
      for (const key in urlOptions) {
        if (urlOptions.hasOwnProperty(key)) {
          const value = urlOptions[key];
          currentPath += `${key}=${value}&`;
        }
      }
      currentPath = currentPath.substring(0, currentPath.length - 1);
      let currentPageConfig = getCurrentPageConfig();  // 获取页面配置
      const path = returnValue.path || currentPath;
      returnValue.path = util.spliceSharePath(path, '4');
      // 如果页面代码未设置分享标题，使用后台设置的分享标题。
      returnValue.title = returnValue.title || (currentPageConfig && currentPageConfig.share_title && currentPageConfig.share_title.trim()) || '';
      return returnValue;
    };
  }

  // 在onLoad中监听接口返回
  let _onLoad = onLoad;
  _config.onLoad = function(options) {
    setTitle = setTitle.bind(this);
    getCurrentPageConfig = getCurrentPageConfig.bind(this);
    WxNotificationCenter.addNotification('getPageCommonConfig', setTitle, this);
    _onLoad && typeof _onLoad === 'function' && _onLoad.call(this, options);
    // TODO, 记录时间
  };

  let _onShow = onShow;
  _config.onShow = function() {
    if (config.module === 'ws_micro_shop') {
      Number(config.spec_type) === 1 && setTitle();
    } else {
      setTitle();
    }
    app.v8_last_page_show_time = Date.now();
    _onShow && typeof _onShow === 'function' && _onShow.call(this);
  };

  let _onHide = onHide;
  _config.onHide = function() {
    app.v8_last_page_hide_time = Date.now();
    util.statRequest({
      pt: getCurrentPages().pop().route,
      pm: JSON.stringify(getCurrentPages().pop().options),
      tm: (app.v8_last_page_hide_time - app.v8_last_page_show_time) / 1000,
      tp: 1,
      cn: 'view',
    });
    _onHide && typeof _onHide === 'function' && _onHide.call(this);
  };

  let _onUnload = onUnload;
  _config.onUnload = function() {
    app.v8_last_page_unload_time = Date.now();

    let pages = getCurrentPages() || [];
    let currentPage = pages.length > 0 ? pages[pages.length - 1] : {};
    let pagePath = currentPage.route || '';
    let pageOptions = currentPage.options || {};
    let timeSpan = (app.v8_last_page_unload_time - app.v8_last_page_show_time) / 1000;
    pagePath && util.statRequest({
      pt: pagePath,
      pm: JSON.stringify(pageOptions),
      tm: timeSpan,
      cn: 'view',
      tp: 1,
    });
    _onUnload && typeof _onUnload === 'function' && _onUnload.call(this);
  };

  let setTitle = function(info) {
    let currentPageConfig =  getCurrentPageConfig(info);
    currentPageConfig && currentPageConfig.name && currentPageConfig.name.trim() && ((config.module === 'ws_micro_shop' && Number(config.spec_type) === 1) || config.module != 'ws_micro_shop')
    && wx.setNavigationBarTitle({
      title: currentPageConfig.name,
    });
  };

  // 获取页面配置，目前包括分享标题、导航栏标题。
  let getCurrentPageConfig = function(info) {
    let pageCommonConfig = wx.getStorageSync('pageCommonConfig');
    let pages = getCurrentPages();
    let url = pages[pages.length - 1] && pages[pages.length - 1].route;
    let moduleName = app.modules || '';
    let pageConfig = !info
      ? (pageCommonConfig && pageCommonConfig[moduleName + '_pageCommonConfig'])
      : info[moduleName + '_pageCommonConfig'];
    let index = pageConfig && pageConfig instanceof Array && pageConfig.length > 0 && pageConfig.findIndex((item) => {
      let path = item.path.indexOf('/') === 0 ? item.path.slice(1) : item.path;
      return path === url;
    });
    return index >= 0 ? pageConfig[index] : '';
  };

  return originalPage(_config);
};

for (let i = 0; i < config.appJson.length; i++) {
  const module = config.appJson[i].module;
  let globalConfig = {};
  try {
    globalConfig = require(`${module}/global`);
  } catch (error) {
    console.warn('no global.js found in ', module);
  }
  extendAppConfig(globalConfig, appConfig);
}
App(appConfig);
